<!-- 代码编辑器 https://github.com/surmon-china/vue-codemirror -->
<template>
    <codemirror
        v-model="currentValue"
        v-bind="attrs"
        :extensions="currentExtensions"
    />
</template>

<script>
import { defineComponent, toRefs, computed, onMounted } from 'vue'
import { isDark } from '@/libs/dark'
import { Codemirror } from 'vue-codemirror'
import { oneDark } from '@codemirror/theme-one-dark'
// 代码格式化/美化
import { js_beautify } from 'js-beautify'

export default defineComponent({
    name: 'CodeEditor',
    components: {
        Codemirror
    },
    props: {
        modelValue: {
            type: String,
            default: ''
        },
        // 扩展
        extensions: {
            type: Array,
            default: () => ([])
        }
    },
    emits: [
        'update:modelValue'
    ],
    setup(props, { emit, attrs }) {
        const { modelValue, extensions } = toRefs(props)

        const currentValue = computed({
            get: () => modelValue.value,
            set: val => emit('update:modelValue', val)
        })

        const currentExtensions = computed(() => {
            const options = []
            if (isDark.value) options.push(oneDark)
            options.push(...extensions.value)
            return options
        })

        onMounted(() => {
            jsBeautify()
        })

        const jsBeautify = () => {
            currentValue.value = js_beautify(currentValue.value)
        }

        return {
            attrs,
            currentValue,
            currentExtensions,

            jsBeautify
        }
    }
})
</script>
